package org.apache.ocean.udp;

import java.util.*;
import java.net.*;

/**
 *
 * @author jasonr
 */
public class MulticastClient {
  Map<Integer,MulticastSocket> multicastSocketMap = new HashMap<Integer,MulticastSocket>();
  
  public MulticastClient() {
    
  }
  
  public void close() {
    for (MulticastSocket multicastSocket : multicastSocketMap.values()) {
      try {
        multicastSocket.leaveGroup(UDPConstants.getMulticastAddress());
        multicastSocket.close();
      } catch (Throwable throwable) {
        
      }
    }
  }
  
  private void sendMulticast(UDPMessage message) throws Exception {
    for (Map.Entry<Integer,MulticastSocket> entry : multicastSocketMap.entrySet()) {
      int port = entry.getKey().intValue();
      sendMulticast(port, entry.getValue(), message);
    }
  }
  
  private void sendMulticast(int port, MulticastSocket multicastSocket, UDPMessage message) throws Exception {
    InetSocketAddress address = new InetSocketAddress(UDPConstants.getMulticastAddress(), port);
    DatagramPacket packet = message.toPacket(address);
    multicastSocket.send(packet);
  }
}
